<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 欠费缴纳
 */
class OweOrder extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'owe_order';



    /**
     * 订单欠费信息 （关联）
     */
    public function getOrderOweInfo()
    {
        return $this->hasMany(OweOrderRecord::class, 'order_id', 'id');
    }

    /**
     * 缴纳的欠费列表
     * @param $authorrization ：用户 token  可选
     * @param page 页数 默认为1
     * @param limit 限制条数 默认 10
     * @param keywords 检索条件
     * @param is_pay 支付状态 1 未支付 2 已支付    3支付异常， 4 订单已失效 5 .已退款
     * @param payment 支付方式  1 微信支付   2 积分抵扣  3其他
     */
    public function lists($keywords, $payment, $is_pay, $start_time, $end_time, $limit = 10)
    {
        $res =  $this->from($this->getTable() . ' as o')
            ->select('o.id', 'o.user_id', 'o.order_number', 'o.user_id', 'o.account_id', 'o.score', 'o.price', 'o.is_pay', 'o.payment', 'o.create_time', 'o.change_time', 'l.account', 'l.username')
            ->join('user_account_lib as l', 'l.id', '=', 'o.account_id')
            ->where(function ($query) use ($keywords) {
                if (!empty($keywords)) {
                    $query->Orwhere('order_number', 'like', '%' . $keywords . '%')
                        ->Orwhere('username', 'like', '%' . $keywords . '%')
                        ->Orwhere('account', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($start_time, $end_time, $payment, $is_pay) {
                if ($payment) {
                    $query->where('payment', $payment);
                }
                if ($is_pay) {
                    $query->where('is_pay', $is_pay);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('o.create_time', [$start_time, $end_time]);
                }
            })
            ->with('getOrderOweInfo')
            ->orderByDesc('o.id')
            ->paginate($limit)
            ->toArray();
        return $res;
    }
}
